package com.lzx.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzx.reggie.dto.DishDto;
import com.lzx.reggie.entity.Dish;
import com.lzx.reggie.entity.DishFlavor;
import com.lzx.reggie.service.DishFlavorService;
import com.lzx.reggie.service.DishService;
import com.lzx.reggie.mapper.DishMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 86176
 * @description 针对表【dish(菜品管理)】的数据库操作Service实现
 * @createDate 2024-07-11 15:15:28
 */
@Service
@RequiredArgsConstructor
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish>
        implements DishService {

    private final DishFlavorService dishFlavorService;

    /**
     * 新增菜品，同时保存相应的口味数据
     *
     * @param dishDto
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        //1.保存菜品的基本信息到dish表
        this.save(dishDto);

        //2.保存菜品的口味信息到dish_flavor表
        //2.1由于只传入了name和value，没有传id，所以我们要把id获取出来
        Long dishId = dishDto.getId();//菜品id
        //2.2处理数据
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());
        //2.3批量保存
        dishFlavorService.saveBatch(flavors);
    }

    /**
     * 拓展查询菜品的方法，用于查询菜品信息和口味信息
     *
     * @param id
     * @return
     */
    @Override
    public DishDto getByIdWithFlavor(Long id) {
        DishDto dishDto = new DishDto();

        //1.查询基本信息，dish
        Dish dish = this.getById(id);

        BeanUtils.copyProperties(dish, dishDto);

        //2.查询当前菜品对应的口味信息，dish_flavor
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);

        dishDto.setFlavors(flavors);

        return dishDto;
    }

    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {
        //1.更新基本信息，dish
        this.updateById(dishDto);

        //2.更新口味信息，dish_flavor
        //2.1先清理当前菜品对应口味--delete
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());

        dishFlavorService.remove(queryWrapper);

        //2.2再添加当前提交的口味信息--insert
        List<DishFlavor> flavors = dishDto.getFlavors();

        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);

    }
}




